package com.zlove.common.view;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;

import com.zlove.commontool.R;

public class FragmentPaperView extends RelativeLayout {
	Context mContext;
	View rootview;
	private RelativeLayout rl_nav;
	private SyncHorizontalScrollView mHsv;// 可以让标题滑动的空间
	private RadioGroup rg_nav_content;// tabs
	private ImageView iv_nav_indicator;// 标题滑标
	private ImageView iv_nav_left;// 标题左指示标
	private ImageView iv_nav_right;// 标题右指示表
	private ViewPager mViewPager;
	private int indicatorWidth;
	private FragmentPagerAdapter mFragmentPagerAdapter;
	private LayoutInflater mInflater;
	protected int currentIndicatorLeft = 0;// 滑标的当前x坐标
	OnPageChangeListener onPageChangeListener;

	public enum Style {
		defult, two, three
	}

	Style style = Style.defult;
	// 默认的资源//

	public String[] tabTitle = { "选项1", "选项2", "选项3" };
	public int mTabcount = 3;// 同时完整显示的标题的数目,(为2时有点bug，title不能随动,可能已修复)
	private int mTitleRadioButtonResoursId = R.layout.fragmentpaperview_title_button;// radioButton的样式

	public FragmentPaperView(Context context) {
		super(context);
		mContext = context;
		init();
	}

	public FragmentPaperView(Context context, int maxsize) {
		super(context);
		mContext = context;
		mTabcount = maxsize;
		init();

	}

	public FragmentPaperView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		TypedArray a = context.obtainStyledAttributes(attrs,
				R.styleable.FragmentPaperView);
		mTabcount = a.getInt(R.styleable.FragmentPaperView_tabCount, mTabcount);
		a.recycle();
		init();
	}

	public FragmentPaperView(Context context, AttributeSet attrs, int defstyle) {
		super(context, attrs, defstyle);
		mContext = context;
		init();
	}

	void init() {
		rootview = inflate(mContext, R.layout.fragmentpaperview, this);
		findViewById();
		initView();
		setListener();
	}

	private void findViewById() {
		rl_nav = (RelativeLayout) findViewById(R.id.rl_nav);
		mHsv = (SyncHorizontalScrollView) findViewById(R.id.mHsv);
		rg_nav_content = (RadioGroup) findViewById(R.id.rg_nav_content);
		iv_nav_indicator = (ImageView) findViewById(R.id.iv_nav_indicator);
		iv_nav_left = (ImageView) findViewById(R.id.iv_nav_left);
		iv_nav_right = (ImageView) findViewById(R.id.iv_nav_right);
		mViewPager = (ViewPager) findViewById(R.id.mViewPager);
	}

	private void initView() {
		DisplayMetrics dm = new DisplayMetrics();
		((Activity) mContext).getWindowManager().getDefaultDisplay()
				.getMetrics(dm);
		indicatorWidth = dm.widthPixels / mTabcount;
		ViewGroup.LayoutParams cursor_Params = iv_nav_indicator
				.getLayoutParams();
		cursor_Params.width = indicatorWidth;// 初始化滑动下标的宽
		iv_nav_indicator.setLayoutParams(cursor_Params);

		mHsv.setSomeParam(rl_nav, iv_nav_left, iv_nav_right,
				(Activity) mContext);

		// 获取布局填充器
		mInflater = (LayoutInflater) mContext
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		// 另一种方式获取
		// LayoutInflater mInflater = LayoutInflater.from(this);

		initNavigationHSV(mTitleRadioButtonResoursId);
	}

	/****
	 * 设置标题页
	 * 
	 * @param titles
	 *            标题的名字集合
	 * @param tablayoutid
	 *            自定义的RadioButton的xml资源文件的id
	 */
	public void setTitle(String[] titles, int tablayoutid) {
		tabTitle = titles;
		if (tablayoutid != 0)
			mTitleRadioButtonResoursId = tablayoutid;
		initView();
	}

	/***
	 * 初始化title的标签，
	 */
	private void initNavigationHSV(int tablayoutid) {

		rg_nav_content.removeAllViews();

		for (int i = 0; i < tabTitle.length; i++) {

			RadioButton rb = (RadioButton) mInflater.inflate(tablayoutid, null);
			rb.setId(i);
			rb.setText(tabTitle[i]);
			rb.setLayoutParams(new LayoutParams(indicatorWidth,
					LayoutParams.MATCH_PARENT));

			rg_nav_content.addView(rb);
		}

	}

	/**
	 * 设置viewPaper的缓存长度，可以保存更多的fragment的状态，不是很好的办法 ，慎用
	 */
	public void setViewPaperSaveSize(int size) {
		mViewPager.setOffscreenPageLimit(size);
	}

	public void setCurrentTab(int position) {
		if (rg_nav_content != null && rg_nav_content.getChildCount() > position) {
			((RadioButton) rg_nav_content.getChildAt(position)).performClick();
		}
	}

	public int getCurrtentFragment() {

		// Fragment fragment = getSupportFragmentManager().findFragmentByTag(
		// "android:switcher:" + R.id.viewpager + ":" +
		// viewpager.getCurrentItem() );

		return mViewPager.getCurrentItem();
	}

	private void setListener() {

		mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {

				setCurrentTab(position);
				if (onPageChangeListener != null) {
					onPageChangeListener.onPageSelected(position);
				}
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				if (onPageChangeListener != null) {
					onPageChangeListener.onPageScrolled(arg0, arg1, arg2);
				}
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				if (onPageChangeListener != null) {
					onPageChangeListener.onPageScrollStateChanged(arg0);
				}
			}
		});

		rg_nav_content
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {

						if (rg_nav_content.getChildAt(checkedId) != null) {

							TranslateAnimation animation = new TranslateAnimation(
									currentIndicatorLeft,
									((RadioButton) rg_nav_content
											.getChildAt(checkedId)).getLeft(),
									0f, 0f);
							animation.setInterpolator(new LinearInterpolator());
							animation.setDuration(100);
							animation.setFillAfter(true);

							// 执行位移动画
							iv_nav_indicator.startAnimation(animation);

							mViewPager.setCurrentItem(checkedId); // ViewPager
																	// 跟随一起 切换

							// 记录当前 下标的距最左侧的 距离
							currentIndicatorLeft = ((RadioButton) rg_nav_content
									.getChildAt(checkedId)).getLeft();

							if (tabTitle.length > mTabcount) {
								for (String a : tabTitle) {
									// System.out.println(a);
								}
								mHsv.smoothScrollTo(
										(checkedId > 1 ? ((RadioButton) rg_nav_content
												.getChildAt(checkedId))
												.getLeft() : 0)
												- ((RadioButton) rg_nav_content
														.getChildAt(2))
														.getLeft(), 0);
							}
						}
					}
				});
	}

	public void setFragmentPagerAdapter(
			FragmentPagerAdapter mFragmentPagerAdapter) {
		this.mFragmentPagerAdapter = mFragmentPagerAdapter;
		mViewPager.setAdapter(mFragmentPagerAdapter);
		// invalidate();
	}

	public void setOnPageChangeListener(
			OnPageChangeListener onPageChangeListener) {
		this.onPageChangeListener = onPageChangeListener;
	}
}
